package com.ll.xiaonew.commons.core.utils;

import com.alibaba.fastjson.JSON;
import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.ll.xiaonew.commons.core.dto.UserToken;
import org.springframework.context.annotation.Configuration;

import java.util.Date;

/**
 * @author new
 * @date 2022/12/5 20:26
 */
@Configuration
public class TokenUtils {
    /**
     *  设置token过期时间
     */
    private static final long TOKEN_TIME_OUT = 60*60*24*1000;

    /**
     * 设置token签名
     */
    private static final Algorithm SIGN = Algorithm.HMAC256("xiaoNewStuSys");

    private static final String USER_TOKEN = "token";

    /**
     * 创建token
     * @param userToken
     * @return
     */
    public static String createToken(UserToken userToken){
        String json = JSON.toJSONString(userToken);

//        Calendar calendar = Calendar.getInstance();
//        calendar.add(Calendar.SECOND,86400);

        // 2.创建JWTbuilder
        JWTCreator.Builder builder = JWT.create();

        // 3.设置头，负载，签名
        String token = builder
//				.withHeader(map) 设置头信息，可以不设置有默认值
                .withClaim(USER_TOKEN,json)
                .withExpiresAt(new Date(System.currentTimeMillis()+TOKEN_TIME_OUT)) // 设置令牌超时时间
                .sign(SIGN);// 设置用户签名
        return token;
    }

    /**
     * 校验token
     * @param token
     * @return
     * @throws JWTVerificationException
     */
    public static DecodedJWT checkToken(String token) throws JWTVerificationException {
        return JWT.require(SIGN).build().verify(token);
    }

    /**
     * 校验token，返回userToken对象
     * @param usersToken
     * @return UserToken
     */
    public static UserToken getUserToken(String usersToken){
        DecodedJWT decodedJWT = checkToken(usersToken);
        String token = decodedJWT.getClaim(USER_TOKEN).asString();
        UserToken userToken = JSON.parseObject(token,UserToken.class);
        return userToken;
    }
}
